package com.bailian.app.controller.Apis;

import com.bailian.common.annotation.Anonymous;
import com.bailian.common.core.controller.BaseController;
import com.bailian.common.core.domain.AjaxResult;
import com.bailian.system.domain.BlPhoneUser;
import com.bailian.system.service.IBlPhoneUserService;
import com.bailian.app.service.WechatMiniProgramService;
import com.bailian.common.config.BaiLianConfig;
import com.bailian.common.utils.file.FileUploadUtils;
import com.bailian.common.utils.file.FileUtils;
import com.bailian.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户信息控制器
 * 
 * @author bailian
 */
@Api(tags = "用户信息相关接口")
@RestController
@RequestMapping("/app/api/user")
public class UserController extends BaseController {

    @Autowired
    private IBlPhoneUserService phoneUserService;
    
    @Autowired
    private WechatMiniProgramService wechatService;
    
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 获取个人信息（通过token）
     */
    @Anonymous
    @ApiOperation("获取个人信息")
    @GetMapping("/info")
    public AjaxResult getUserInfo(HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                return error("token不能为空");
            }
            
            // 如果token以"Bearer "开头，去掉前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            Long userId = wechatService.getUserIdFromToken(token);
            if (userId == null) {
                return error("token无效");
            }
            
            BlPhoneUser user = phoneUserService.selectBlPhoneUserById(userId);
            if (user == null) {
                return error("用户不存在");
            }
            return success(user);
        } catch (Exception e) {
            return error("获取用户信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取个人信息（通过用户ID）
     */
    @ApiOperation("根据用户ID获取个人信息")
    @GetMapping("/info/{userId}")
    public AjaxResult getUserInfoById(@ApiParam("用户ID") @PathVariable Long userId) {
        try {
            BlPhoneUser user = phoneUserService.selectBlPhoneUserById(userId);
            if (user == null) {
                return error("用户不存在");
            }
            return success(user);
        } catch (Exception e) {
            return error("获取用户信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 修改个人信息
     */
    @Anonymous
    @ApiOperation("修改个人信息")
    @PutMapping("/update")
    public AjaxResult updateUserInfo(@RequestBody BlPhoneUser phoneUser, HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                return error("token不能为空");
            }
            
            // 如果token以"Bearer "开头，去掉前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            // 验证token并获取用户ID
            Long userId = wechatService.getUserIdFromToken(token);
            if (userId == null) {
                return error("token无效");
            }
            
            // 确保只能修改自己的信息
            if (phoneUser.getUserId() == null || !phoneUser.getUserId().equals(userId)) {
                phoneUser.setUserId(userId);
            }
            
            int result = phoneUserService.updateBlPhoneUser(phoneUser);
            if (result > 0) {
                return success("修改成功");
            } else {
                return error("修改失败");
            }
        } catch (Exception e) {
            return error("修改失败：" + e.getMessage());
        }
    }

    /**
     * 上传用户头像
     */
    @Anonymous
    @ApiOperation("上传用户头像")
    @PostMapping("/uploadAvatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            // 从请求头中获取token
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                return error("token不能为空");
            }
            
            // 如果token以"Bearer "开头，去掉前缀
            if (token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
            
            // 验证token并获取用户ID
            Long userId = wechatService.getUserIdFromToken(token);
            if (userId == null) {
                return error("token无效");
            }
            
            // 验证文件
            if (file == null || file.isEmpty()) {
                return error("请选择要上传的头像文件");
            }
            
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".jpg") 
                && !originalFilename.toLowerCase().endsWith(".jpeg") 
                && !originalFilename.toLowerCase().endsWith(".png"))) {
                return error("头像文件格式不正确，请上传jpg、jpeg或png格式的图片");
            }
            
            // 检查文件大小（限制为5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return error("头像文件大小不能超过5MB");
            }
            
            // 获取头像上传路径
            String avatarPath = BaiLianConfig.getAvatarPath();
            
            // 上传文件
            String fileName = FileUploadUtils.upload(avatarPath, file);
            String url = serverConfig.getUrl() + fileName;
            
            // 更新用户头像信息
            BlPhoneUser user = new BlPhoneUser();
            user.setUserId(userId);
            user.setHeadPicture(url);
            
            int result = phoneUserService.updateBlPhoneUser(user);
            if (result > 0) {
                AjaxResult ajax = AjaxResult.success("头像上传成功");
                ajax.put("url", url);
                ajax.put("fileName", fileName);
                ajax.put("newFileName", FileUtils.getName(fileName));
                ajax.put("originalFilename", originalFilename);
                return ajax;
            } else {
                return error("头像上传失败");
            }
        } catch (Exception e) {
            return error("头像上传失败：" + e.getMessage());
        }
    }
} 